﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Twi.COMMON.HTTP;
using System.Windows;
using Twi.COMMON.WPF;
using System.Xml.Linq;
using System.Configuration;

namespace Twi.COMMON.WPF
{

    /// <summary>
    /// 请求处理
    /// </summary>
    public class ProcessRequest
    {

        /// <summary>
        /// 获取当前菜单名称
        /// </summary>
        public static Func<string> GetMenuName;

        public static int ERR_HANDLING = 0; //0: 默认，弹出窗口； 1:不弹出窗口，记录在日志里


        public static RequestResult Process(HttpResponseMessage res, Action<Twi.COMMON.WPF.ResponseMessageInfo> processDelegate, string errorMsgTempalte = "{0}")
        {
            if (res != null && res.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var resInfo = res.Content.ReadAsHttpResponseMessageInfo();
                if (resInfo.Status == RequestResult.ServerException)
                {
                    if (ERR_HANDLING == 0)
                    {
                        //Twi.COMMON.WPF.ErrorInfo ei = new ErrorInfo(resInfo.Exception);
                        //ei.Show();
                        Twi.COMMON.WPF.TwiMsg.Error(resInfo.Message);
                    }
                    else
                    {
                        //Log.LogException(resInfo.Exception);
                    }
                    return RequestResult.ServerException;
                }
                else if (resInfo.Status == RequestResult.ServerExceptionCatched)
                {
                    if (ERR_HANDLING == 0)
                    {
                        //MessageBox.Show(resInfo.Exception, "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                        Twi.COMMON.WPF.TwiMsg.Error(resInfo.Message);
                    }
                    else
                    {
                        //Log.LogException(resInfo.Exception);
                    }
                    return RequestResult.ServerExceptionCatched;
                }
                else if (resInfo.Status == RequestResult.ServerResultUnsuccess)
                {
                    if (ERR_HANDLING == 0)
                    {
                        //MessageBox.Show(string.Format(errorMsgTempalte, resInfo.Message), "系统提示");
                        Twi.COMMON.WPF.TwiMsg.Error(resInfo.Message);
                    }
                    else
                    {
                        //Log.LogException(resInfo.Exception);
                    }
                    return RequestResult.ServerResultUnsuccess;
                }
                else if (resInfo.Status == RequestResult.ServerResultUnsuccessOKCancel)
                {
                    if (MessageBox.Show(string.Format(errorMsgTempalte, resInfo.Message), "", MessageBoxButton.OKCancel, MessageBoxImage.Question) == MessageBoxResult.OK)//执行下一步操作
                    {
                        return RequestResult.ServerResultUnsuccessOK;
                    }
                    else
                    {
                        return RequestResult.ServerResultUnsuccessCancel;
                    }
                }
                else if (resInfo.Status == RequestResult.ServerResultUnsuccessYesNo)
                {
                    if (MessageBox.Show(string.Format(errorMsgTempalte, resInfo.Message), "", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)//执行下一步操作
                    {
                        return RequestResult.ServerResultUnsuccessYes;
                    }
                    else
                    {
                        return RequestResult.ServerResultUnsuccessNo;
                    }
                }
                else if (resInfo.Status == RequestResult.ClientVersionException)  //客户端版本异常
                {
                    //关闭重新升级
                    if (Tools.GAffirmYesNo(string.Format(errorMsgTempalte, resInfo.Exception)))
                    {
                        try
                        {
                            string launchPath = System.AppDomain.CurrentDomain.BaseDirectory + "\\..\\Launch.exe";
                            {
                                //如果升级程序不存在则返回
                                if (System.IO.File.Exists(launchPath))
                                {
                                    System.Diagnostics.Process.Start(launchPath);
                                }
                            }
                            System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName(ConfigurationManager.AppSettings["StartupProgram"]);
                            //杀死进程并继续
                            foreach (System.Diagnostics.Process proc in processes)
                            {
                                proc.Kill();
                            }
                        }
                        catch
                        {
                            return RequestResult.ClientVersionException;
                        }
                    }
                    else
                    {
                        return RequestResult.ClientVersionException;
                    }
                }


                InitUriParam(res);
                processDelegate(resInfo);
                return RequestResult.ServerResultSuccess;
            }
            else
            {
                if (res != null) //用于编码环境下调用验证
                {
                    if (res.StatusCode.ToString() == "Unauthorized")
                    {
                        MessageBox.Show("API Key验证未通过或服务器端未插入有效的加密锁！", "验证失败");
                    }
                    else
                    {
                        MessageBox.Show(res.StatusCode.ToString(), "通讯故障");
                    }
                }
                return RequestResult.CommunicationFailure;//表示通讯错误
            }
        }



        private static void InitUriParam(HttpResponseMessage res)
        {
            string menuName = "未知";
            if (GetMenuName != null)
            {
                menuName = GetMenuName();
            }
            res.Request.Properties.Add(new XElement("IP", ConstClass.IP));
            res.Properties.Add(new XElement("IP", ConstClass.IP));
            //uri += string.Format("&IP={0}", ConstClass.IP);
            //uri += string.Format("&MACAddress={0}", ConstClass.MACAddress);
            //uri += string.Format("&MenuName={0}", menuName);
            //uri += string.Format("&RequestKey={0}", Guid.NewGuid().ToString("N"));
            //uri += string.Format("&OperateType={0}", 1);         
            //uri += string.Format("&OperateName={0}", ConstClass.OperateName);



        }

    }
}
